import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import './styles/index.css'
import 'default-passive-events'
import { useTheme } from './store/theme'
import { formatTimestamp } from '@/utils/date'

// 导入Element Plus图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 导入i18n
import i18n from './locales'

// 导入Element Plus语言包
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'

// 导入路由守卫
import './router/guard'

// 导入用户状态管理
import { useUser } from './store/user'

// 获取当前语言
const getCurrentLocale = () => {
  const storedLocale = localStorage.getItem('locale')
  return storedLocale || 'zh-CN'
}

const app = createApp(App)
const pinia = createPinia()

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 根据当前语言设置Element Plus的语言包
const currentLocale = getCurrentLocale()
if (currentLocale === 'zh-CN') {
  app.use(ElementPlus, { locale: zhCn })
} else {
  app.use(ElementPlus, { locale: en })
}

// 定义全局方法
app.config.globalProperties.$formatTimestamp = formatTimestamp

app.use(pinia)
app.use(i18n)
app.use(router)

// 初始化主题
const { initTheme } = useTheme()
initTheme()

// 检查是否已登录
const token = localStorage.getItem('accessToken')
if (token) {
  // 初始化数据
  const { initData } = useUser()
  initData()
} else {
  // 未登录，跳转到登录页
  router.push('/login')
}

app.mount('#app')
